package com.ruoyi.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.dto.SysUserDTO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


/**
 * 登录验证
 */
@RestController
public class SysLoginController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysUserService sysUserService;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody SysUserDTO userDTO) {
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (userDTO.getUserName() != null) {
            lambdaQueryWrapper.eq(SysUser::getUserName, userDTO.getUserName());
        }

        SysUser sysUser = sysUserService.getOne(lambdaQueryWrapper);

        if (sysUser != null && sysUser.getPassword().equals(userDTO.getPassword())) {
            AjaxResult ajax = AjaxResult.success();

            // 生成令牌
            String token = tokenService.createToken(String.valueOf(sysUser.getUserId()));
            ajax.put(Constants.TOKEN, token);
            return ajax;
        } else {
            throw new RuntimeException();
        }
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters(HttpServletRequest request) {
        String userId = tokenService.getToken(request);

        return AjaxResult.success(menuService.buildMenus(Long.valueOf(userId)));
    }
}
